package cn.lxh.template;

import cn.lxh.properties.IdVerificationProperties;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;

/**
 * @author lxh Create Time: 2023/12/30 13:06
 * 身份证验证工具类
 */
@Slf4j
public class IdVerificationTemplate {

    private IdVerificationProperties idVerificationProperties;

    public IdVerificationTemplate(IdVerificationProperties idVerificationProperties) {
        this.idVerificationProperties = idVerificationProperties;
    }

    /**
     * 验证身份证
     * @param name
     * @param idCardNum
     * @return
     * @throws IOException
     */
    public Boolean verifyIDCard(String name, String idCardNum) throws IOException {
        String url = idVerificationProperties.getUrl();
        // 获取appCode链接：https://market.console.aliyun.com/
        String appCode = idVerificationProperties.getAppCode();
        String result = "";
        RequestBody formBody = new FormBody.Builder().add("name", name).add("idCardNum", idCardNum).build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(formBody).build();

        Call call = new OkHttpClient().newCall(request);
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException e) {
            System.out.println("execute failed, message:" + e.getMessage());
        }

        assert response != null;
        if (!response.isSuccessful()) {      // 当返回结果发生错误时
            // 状态码为403时一般是套餐包用尽，需续购；注意：续购不会改变秘钥（appCode），仅增加次数
            // 续购链接：https://market.aliyun.com/products/57000002/cmapi025518.html
            System.out.println("request failed----" + "返回状态码" + response.code() + ",message:" + response.message());
        }
        result = response.body().string();    //此处不可以使用toString()方法，该方法已过期
        log.info("验证身份证结果: {}", result);
        if (response.code() != 0000) {
            return false;
        }
        return true;
    }

}
